const express = require("express");
const app = express();
app.use(express.urlencoded({
    extended:false
}))
app.use(express.static(__dirname))
app.use(function(req,res,next){
    res.set("Access-Control-Allow-Origin","*");
    next();
})
const userList = [
    {
        id:"abcadsfasdf",
        username:"zhangsan",
        password:"abc",
        voteNum:10
    },
    {
        id:"alksjdflkasdf",
        username:"lisi",
        password:"123",
        voteNum:20
    }
]
app.get("/login",(req,res)=>{
    const {username,password} = req.query;
    const info = userList.find(v=>v.username===username && v.password === password);
    if(info){
        res.send("<h3>恭喜"+info.username+"登陆成功！</h3>")
        // res.json({
        //     ok:1,
        //     msg:"get->login",
        //     info
        // })
    }else{
        res.json({
            ok:-1,
            msg:"get->login"
        })
    }

});
app.post("/login",(req,res)=>{
    const {username,password} = req.body;
    const info = userList.find(v=>v.username===username && v.password===password);
    if(info){
        res.redirect("/success.html")
        // res.send("<h3>恭喜"+info.username+"登陆成功！</h3>")
        // res.json({
        //     ok:1,
        //     msg:"get->login",
        //     info
        // })
    }else{
        res.json({
            ok:-1,
            msg:"get->login"
        })
    }
});

app.get("/",(req,res)=>{
    res.send(`
        <div>
            ${
                userList.map(item=>(`
                     <a href="/vote?id=${item.id}">${item.username}(${item.voteNum})</a><br/>
                `)).join("")
            }
        </div>
    `)
})
app.get("/vote",(req,res)=>{
    const {id} = req.query;
    const info = userList.find(v=>v.id === id);
    info.voteNum++;
    res.redirect("/")
})
app.get("/userList",(req,res)=>{
    res.json(userList);
})
app.get("/sendVote/:id",(req,res)=>{
    const {id} = req.params;
    const info = userList.find(v=>v.id === id);
    info.voteNum++;
    res.json({
        ok:1,
        info,
        msg:"投票成功"
    })
})


app.listen(8090,()=>{
    console.log("success");
})